package com.lang.dao.impl;

import com.lang.dao.AddressDao;
import com.lang.entity.Address;
import com.lang.utils.C3P0Utils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/*
 * @Date : 2024/3/14 10:47
 * @Created by Lang
 * @ProjectName : LclShop
 */
public class AddressDaoImpl implements AddressDao {
    private QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());

    @Override
    public List<Address> getAddress(int uId) {
        String sql = "select * from address where u_id = ?";
        try {
            return runner.query(sql, new BeanListHandler<>(Address.class), uId);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int addAddress(Address a) {
        String sql = "insert into address(u_id,a_name,a_phone,a_detail,a_state) " +
                "values(?,?,?,?,?)";
        try {
            return runner.update(sql, a.getU_id(), a.getA_name(), a.getA_phone(),
                    a.getA_detail(), a.getA_state());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int deleteAddressByAid(String aid) {
        String sql = "delete from address where a_id = ?";
        try {
            return runner.update(sql, aid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int updateAddress(Address address) {
        String sql = "update address set a_name = ?,a_phone = ?, a_detail = ? where a_id = ?";
        try {
            return runner.update(sql, address.getA_name(), address.getA_phone(), address.getA_detail(), address.getA_id());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int updateDefault(String aid) {
        String sql = "update address set a_state = 1 where a_id = ?";
        try {
            return runner.update(sql, aid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int updateNoDefault(int uid) {
        String sql = "update address set a_state = 0 where u_id = ?";
        try {
            return runner.update(sql, uid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int deleteAddressByUid(String id) {
        String sql = "DELETE from `address` WHERE u_id = ?";
        try {
            return runner.update(sql, id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
